package com.sdy.redis.driver;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by zzq on 2017-08-23.
 */
@Slf4j
@Service
public class RedisDriver {
    @Autowired
    private RedisTemplate<String, Object> template;

    /**
     * 设置缓存对象
     *
     * @param key
     * @param value
     */
    public void set(String key, Object value) {
        template.opsForValue().set(key, value);
    }

    public void set(String key, Object value, int seconds) {
        template.opsForValue().set(key, value, Duration.ofSeconds(seconds));
    }

    /**
     * 获取缓存对象
     *
     * @param key
     * @return
     */
    public <T> T get(String key, Class<T> clazz) {
        return (T) template.opsForValue().get(key);
    }

    public Boolean setnx(String key, Object value) {
        return template.opsForValue().setIfAbsent(key, value);
    }

    public Boolean setnx(String key, Object value, int seconds) {
        return template.opsForValue().setIfAbsent(key, value, Duration.ofSeconds(seconds));
    }

    /**
     * 删除缓存对象
     *
     * @param key
     */
    public Boolean del(String key) {
        return template.delete(key);
    }

    public Set<String> keys(String regx) {
        return template.keys(regx);
    }

    public Boolean exists(String key) {
        return template.hasKey(key);
    }

    public Long incr(String key) {
        return template.opsForValue().increment(key, 1);
    }

    public Long ttl(String key) {
        return template.getExpire(key, TimeUnit.SECONDS);
    }

    public Boolean expire(String key, Integer seconds) {
        return template.expire(key, seconds, TimeUnit.SECONDS);
    }
    
    public Long sadd(String key, Object... value) {
        return template.opsForSet().add(key, value);
    }

    public Long sremove(String key, Object... value) {
        return template.opsForSet().remove(key, value);
    }

    public Long scard(String key) {
        return template.opsForSet().size(key);
    }

    public Set<Object> smember(String key) {
        return template.opsForSet().members(key);
    }

    public Long rpush(String key, Object value) {
        return template.opsForList().rightPush(key, value);
    }

    public Long llen(String key) {
        return template.opsForList().size(key);
    }

    public List lrange(String key, int start, int end) {
        return template.opsForList().range(key, start, end);
    }

    public Long incr(String key, Long delta) {
        return template.opsForValue().increment(key, delta);
    }
}
